package com.jjwxc.jwjskandriod.fragment;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RadioGroup;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.fastjson.JSON;
import com.jjwxc.jwjskandriod.R;
import com.jjwxc.jwjskandriod.activity.BookManageActivity;
import com.jjwxc.jwjskandriod.activity.MainActivity;
import com.jjwxc.jwjskandriod.adapter.InfoViewHolder;
import com.jjwxc.jwjskandriod.config.Url;
import com.jjwxc.jwjskandriod.framework.base.FFActivity;
import com.jjwxc.jwjskandriod.framework.http.FFNetWork;
import com.jjwxc.jwjskandriod.framework.http.FFNetWorkCallBack;
import com.jjwxc.jwjskandriod.framework.imageloader.FFImageLoader;
import com.jjwxc.jwjskandriod.framework.refresh.XRefreshView;
import com.jjwxc.jwjskandriod.framework.refresh.XRefreshViewFooter;
import com.jjwxc.jwjskandriod.framework.refresh.recyclerview.BaseRecyclerAdapter;
import com.jjwxc.jwjskandriod.framework.utils.FFUtils;
import com.jjwxc.jwjskandriod.framework.utils.PreUtils;
import com.jjwxc.jwjskandriod.framework.utils.StUtils;
import com.jjwxc.jwjskandriod.framework.widget.ToggleRadioButton;
import com.jjwxc.jwjskandriod.model.BookCaseResponse;
import com.jjwxc.jwjskandriod.model.ListBookGroupResponse;
import com.jjwxc.jwjskandriod.model.ScreenResponse;
import com.jjwxc.jwjskandriod.model.VipDistanceResponse;
import com.jjwxc.jwjskandriod.readActivity.ReadActivity;
import com.jjwxc.jwjskandriod.readActivity.bean.CollBookBean;
import com.jjwxc.jwjskandriod.readActivity.utils.UMConstant;
import com.jjwxc.jwjskandriod.widget.GroupPop;
import com.jjwxc.jwjskandriod.widget.LinearLayouDecoration;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * 全部收藏的页面
 */
public class CollectFragment extends Fragment {
    private View view;
    private RadioGroup tabLayout;
    private ImageView img_add;
    private RecyclerView rv_space;
    public static long lastRefreshTime;
    private XRefreshView refreshView;
    private int page = 0;
    private String value;
    private String key;
    private CollectAdapter adapter;

    //定义三种常量  表示三种条目类型
    private final int TYPE_1_IMAGE = 1;
    private final int TYPE_2_IMAGE = 2;
    private int mViewType;

    private final List<BookCaseResponse.DataBean> dateList = new ArrayList<>();
    private String mSelectTab = null;
    private boolean isRefresh = false;
    ScreenResponse screenResponse = new ScreenResponse();

    public CollectFragment(String key, String value) {
        this.key = key;
        this.value = value;
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        if (view == null) {
            view = inflater.inflate(R.layout.fragment_collect, container, false);
            rv_space = view.findViewById(R.id.rv_space);
            tabLayout = view.findViewById(R.id.tab_collect_layout);
            img_add = view.findViewById(R.id.img_add);
            refreshView = view.findViewById(R.id.collect_view);
            rv_space.setNestedScrollingEnabled(false);
            rv_space.setFocusable(false);
            mViewType = PreUtils.getInt("ViewType", 1);

            adapter = new CollectAdapter(getActivity());
            rv_space.setAdapter(adapter);
            refreshView.setPinnedTime(1000);
            refreshView.setMoveForHorizontal(true);
            refreshView.setPullRefreshEnable(true);
            refreshView.setPullLoadEnable(true);
            refreshView.setAutoLoadMore(true);
            adapter.setCustomLoadMoreView(new XRefreshViewFooter(getActivity()));
            refreshView.enableReleaseToLoadMore(true);
            refreshView.enableRecyclerViewPullUp(true);
            refreshView.enablePullUpWhenLoadCompleted(true);
            // 设置上次刷新的时间
            refreshView.restoreLastRefreshTime(lastRefreshTime);

            //设置布局格式
            setViewType(mViewType);
            rv_space.addItemDecoration(new LinearLayouDecoration(getActivity(),
                    LinearLayouDecoration.HORIZONTAL, R.dimen.border8, R.color.transparent));
            getListUserBookcase(null, 0, null);
            onListener();
            getListBookcaseGroup();
            refreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
                @Override
                public void onRefresh(boolean isPullDown) {
                    page = 0;
                    getListUserBookcase(mSelectTab, page, null);
                }

                @Override
                public void onLoadMore(boolean isSilence) {
                    super.onLoadMore(isSilence);
                    page += 1;
                    getListUserBookcase(mSelectTab, page * 20, null);
                }
            });

        }
        return view;
    }

    public void setViewType(int viewType) {
        if (viewType == 1) {

            rv_space.setLayoutManager(new GridLayoutManager(getActivity(), 4));
//            rv_space.addItemDecoration(new LinearLayouDecoration(getActivity(),
//                    LinearLayouDecoration.HORIZONTAL, R.dimen.border8, R.color.transparent));
            Objects.requireNonNull(rv_space.getItemAnimator()).setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题
            MobclickAgent.onEvent(getContext(), UMConstant.PAGE_BOOKSHELF_COVER_MODE);
        } else {
            rv_space.setLayoutManager(new LinearLayoutManager(getActivity()));
//            rv_space.addItemDecoration(new LinearLayouDecoration(getActivity(),
//                    LinearLayouDecoration.HORIZONTAL, R.dimen.border8, R.color.transparent));
            Objects.requireNonNull(rv_space.getItemAnimator()).setChangeDuration(0);// 通过设置动画执行时间为0来解决闪烁问题
            MobclickAgent.onEvent(getContext(), UMConstant.PAGE_BOOKSHELF_LIST_MODE);
        }
        adapter.setType(viewType);
    }

    @Override
    public void onResume() {
        super.onResume();
        if (isRefresh) {
            isRefresh = false;
            getListUserBookcase(mSelectTab, 0, "加载数据...");
        }
        //获取用户是不是VIP
        getVipDistance();
    }

    public void getListBookcaseGroup() {
        ((FFActivity) getActivity()).post(Url.listBookcaseGroup, null, ListBookGroupResponse.class, new FFNetWorkCallBack<ListBookGroupResponse>() {
            @Override
            public void onSuccess(ListBookGroupResponse response) {
                setTabs(tabLayout, getLayoutInflater(), response.getData());
            }

            @Override
            public boolean onFail(ListBookGroupResponse response) {
                return false;
            }
        });


    }

    public void getListUserBookcase(String groupId, int page, String words) {
        if (page == 0) {
            refreshView.setLoadComplete(false);
        }
        if (PreUtils.getBoolean("QING_switch", false)) {
            screenResponse.setIsChildMode(true);
        } else {
            screenResponse.setIsChildMode(false);
        }
        screenResponse.setBookcaseGroupId(groupId);
        screenResponse.setLimit(20);
        screenResponse.setOffset(page);
        ((FFActivity) getActivity()).post(Url.listUserBookcase, words, BookCaseResponse.class,
                new FFNetWorkCallBack<BookCaseResponse>() {
                    @Override
                    public void onSuccess(BookCaseResponse response) {
                        lastRefreshTime = refreshView.getLastRefreshTime();
                        dateList.clear();
                        dateList.addAll(response.getData());
                        if (dateList == null || dateList.size() < 20) {
                            refreshView.setLoadComplete(true);
                        }
                        if (page == 0) {
                            refreshView.stopRefresh();
                            BookCaseResponse.DataBean bean = new BookCaseResponse.DataBean();
                            bean.setBookcaseId("");
                            dateList.add(bean);
                            adapter.setData(dateList);
                        } else {
                            refreshView.stopLoadMore();
                            BookCaseResponse.DataBean bean = new BookCaseResponse.DataBean();
                            bean.setBookcaseId("");
                            dateList.add(bean);
                            adapter.addData(dateList);
                        }

                    }

                    @Override
                    public boolean onFail(BookCaseResponse response) {
                        refreshView.stopLoadMore();
                        refreshView.stopRefresh();
                        refreshView.setLoadComplete(true);
                        return false;
                    }
                }, JSON.toJSONString(screenResponse));
    }

    private void setTabs(RadioGroup tabLayout, LayoutInflater inflater, List<ListBookGroupResponse.DataBean> tabTitlees) {
        tabLayout.removeAllViews();
        for (int i = 0; i < tabTitlees.size(); i++) {
            ToggleRadioButton view = (ToggleRadioButton) inflater.inflate(R.layout.collect_item, null);
            view.setId(i);
            ViewGroup.MarginLayoutParams layoutParams = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, FFUtils.getPx(26));
            layoutParams.setMargins(10, 0, 0, 0);
            view.setLayoutParams(layoutParams);
            if (PreUtils.getBoolean("QING_switch", false) && i == 0) {
                view.setChecked(true);
            }
            view.setText(tabTitlees.get(i).getName());
            tabLayout.addView(view);
        }
        tabLayout.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @SuppressLint("ResourceType")
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (group.getCheckedRadioButtonId() > -1) {
                    mSelectTab = tabTitlees.get(checkedId).getBookcaseGroupId();
                    getListUserBookcase(mSelectTab, 0, "加载数据...");
                } else {
                    mSelectTab = null;
                    getListUserBookcase(mSelectTab, 0, "加载数据...");
                }


            }
        });

    }

    public void onListener() {
        img_add.setOnClickListener(v -> GroupPop.editGroupPop(v, getActivity(), new GroupPop.PopDismissListener() {
            @Override
            public void onOkClick(boolean group) {
                if (group) {
                    getListBookcaseGroup();
                }

            }
        }));

    }

    public String getSelectTab() {
        isRefresh = true;
        return mSelectTab;
    }

    public String getScreenResponse() {

        return JSON.toJSONString(screenResponse);
    }

    public void setScreenResponse(String screen) {
        ScreenResponse response = JSON.parseObject(screen, ScreenResponse.class);
        page = 0;
        screenResponse.setBookType(response.getBookType());
        screenResponse.setSortType(response.getSortType());
        screenResponse.setSubscribeStatus(response.getSubscribeStatus());
        screenResponse.setReadingRate(response.getReadingRate());
        screenResponse.setIsChildMode(PreUtils.getBoolean("QING_switch", false));
        //刷新数据
        getListUserBookcase(mSelectTab, 0, "加载数据...");
    }

    public void setDateList(List<BookCaseResponse.DataBean> dateList) {
        this.dateList.addAll(dateList);
    }


    public class CollectAdapter extends BaseRecyclerAdapter<InfoViewHolder> {
        private Context context;

        private int type; //控制布局类型的变量
        private List<BookCaseResponse.DataBean> mData = new ArrayList<>();


        public CollectAdapter(Context cnt) {
            this.context = cnt;

        }

        @SuppressLint("NotifyDataSetChanged")
        public void addData(List<BookCaseResponse.DataBean> data) {
            if (data != null) {
                if (mData.size() > 0) {
                    mData.remove(mData.size() - 1);
                }
                mData.addAll(data);
                notifyDataSetChanged();
            }
        }

        public void setData(List<BookCaseResponse.DataBean> data) {
            this.mData.clear();
            addData(data);
        }

        /**
         * 创建ViewHolder
         */
        @Override
        public InfoViewHolder onCreateViewHolder(ViewGroup parent, int viewType, boolean isItem) {
            if (viewType == TYPE_1_IMAGE) {
                View mView = LayoutInflater.from(context).inflate(R.layout.info_book_grid_item, parent, false);
                InfoViewHolder viewHolder_text = new InfoViewHolder(mView);
                return viewHolder_text;
            } else if (viewType == TYPE_2_IMAGE) {
                View mView = LayoutInflater.from(context).inflate(R.layout.info_book_list_item, parent, false);
                InfoViewHolder viewHolder_text = new InfoViewHolder(mView);
                return viewHolder_text;
            }
            return null;
        }

        @Override
        public InfoViewHolder getViewHolder(View view) {
            return new InfoViewHolder(view);
        }


        /**
         * 绑定数据：可以直接拿到已经绑定控件的Viewholder对象
         */
        @SuppressLint("SetTextI18n")
        @Override
        public void onBindViewHolder(final InfoViewHolder holder, @SuppressLint("RecyclerView") final int position, boolean isItem) {
            if (mData.size() == position + 1) {
                FFImageLoader.loadImage(context, holder.img_grid_book, R.mipmap.moren_icon);
                holder.txt_grid_book.setVisibility(View.INVISIBLE);
                if (holder.tv_time != null) {
                    holder.tv_time.setVisibility(View.INVISIBLE);
                } else {
                    holder.tv_jindu.setVisibility(View.INVISIBLE);
                }
            } else {
                if (mData.get(position).getBook() != null && !StUtils.isEmpty(mData.get(position).getBook().getCoverImgUrl())) {
                    FFImageLoader.loadImage(context, holder.img_grid_book, mData.get(position).getBook().getCoverImgUrl() + "", mData.get(position).getBookId(), true);
                    holder.txt_grid_book.setText(mData.get(position).getBook().getName());
                    holder.txt_grid_book.setVisibility(View.VISIBLE);
                }

                if (holder.tv_time != null) {
                    if (mData.get(position).getBook() != null) {
                        holder.tv_time.setVisibility(View.VISIBLE);
                        String reading = mData.get(position).getReadingChapterId();
                        if (StUtils.isEmpty(reading) || reading.equals("0")) {
                            holder.tv_time.setText("未开始");
                        } else if (reading.equals(mData.get(position).getBook().getChapterCount() + "")) {
                            holder.tv_time.setText("已读完");
                        } else {
                            holder.tv_time.setText(reading + "章/" + mData.get(position).getBook().getChapterCount() + "章");
                        }
                    }

                } else {
                    if (mData.get(position).getBook() != null) {
                        holder.tv_jindu.setVisibility(View.VISIBLE);
                        String reading = mData.get(position).getReadingChapterId();
                        if (StUtils.isEmpty(reading) || reading.equals("0")) {
                            holder.tv_jindu.setText("未开始");
                        } else if (reading.equals(mData.get(position).getBook().getChapterCount() + "")) {
                            holder.tv_jindu.setText("已读完");
                        } else {
                            holder.tv_jindu.setText(reading + "章/" + mData.get(position).getBook().getChapterCount() + "章");
                        }
                    }
                }
            }
            holder.ll_grid_item.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    Intent intent = new Intent(getActivity(), BookManageActivity.class);
                    intent.putExtra("book_tab", mSelectTab);
                    startActivity(intent);
                    return false;
                }
            });
            holder.ll_grid_item.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (mData.size() == position + 1) {
                        Intent intent = new Intent();
                        intent.setAction(MainActivity.RefreshSuggest);
                        getActivity().sendBroadcast(intent);
                    } else {
                        if (mData.get(position).getBook() != null) {
                            CollBookBean collBookBean = new CollBookBean();
                            collBookBean.set_id(mData.get(position).getBook().getBookId());
                            collBookBean.setAuthor(mData.get(position).getBook().getAuthor());
                            collBookBean.setTitle(mData.get(position).getBook().getName());
                            collBookBean.setShortIntro(StUtils.reBlank(mData.get(position).getBook().getBookIntro()));
                            collBookBean.setCover(mData.get(position).getBook().getCoverImgUrl());
                            if (!StUtils.isEmpty(mData.get(position).getReadingChapterId())) {
                                collBookBean.setChaptersCount(Integer.parseInt(mData.get(position).getReadingChapterId()));
                            }
                            collBookBean.setIsUpdate(true);
                            collBookBean.setMonthSubscribe(mData.get(position).getBook().getIsMonthSubscribe());
                            addToBookShelfUtils(collBookBean);
                        }

                    }
                }
            });


        }


        @Override
        public int getAdapterItemViewType(int position) {
            return type;
        }

        public void setType(int type) {
            this.type = type;
        }

        @Override
        public int getAdapterItemCount() {
            return mData.size();
        }


    }

    public void getVipDistance() {
        new FFNetWork().post(Url.vipDistance, null, new FFNetWorkCallBack<VipDistanceResponse>() {
            @Override
            public void onSuccess(VipDistanceResponse response) {
                if (response.getCode() == 200) {
                    ReadActivity.userIsVip = response.getData() <= 0;
                }
            }

            @Override
            public boolean onFail(VipDistanceResponse response) {
                return false;
            }
        }, VipDistanceResponse.class);
    }

    public void addToBookShelfUtils(CollBookBean collBookBean) {

        Intent intent = new Intent(getActivity(), ReadActivity.class);
        intent.putExtra(ReadActivity.EXTRA_COLL_BOOK, collBookBean);
        intent.putExtra(ReadActivity.EXTRA_IS_COLLECTED, true);
        startActivity(intent);

    }

}

